import { getExam } from '../../utils/util'
export const examTypes = ['混合运算', '乘加乘减', '带余数除法', '除法', '乘法', '三位数加减', '100以内加减', '20以内加减']
const app = getApp()
Page({
  data: {
    time: 1,
    minute: 0,
    second: 0,
    showDJS: false,
    list: [] as any,
    index: 0,
    allTest: 0,
    allRight: 0,
    wrongList: [],
    isFocus: true,
    isShangFocus: true,
    isYuShuFocus: false,
    timer: null as any,
    examTypes,
    typeIndex: 0,
    loading: false,
    submitTimer: 0
  },
  setTime(val: { detail: number }) {
    if (!this.data.showDJS) {
      this.setData({ time: val.detail })
    }
  },
  canStart() {
    return this.data.time > 0 && !this.data.showDJS
  },
  startTest() {
    this.setData({
      list: [], index: 0, wrongList: [], allTest: 0,
      allRight: 0
    })
    if (this.data.showDJS) {
      clearInterval(this.data.timer)
      this.setData({ showDJS: false, timer: null })
      return
    }
    this.chuti()
    this.setData({ showDJS: true })
    this.setData({ minute: this.data.time - 1 })
    this.setData({ second: 59 })
    const mid: any = setInterval(() => {
      const next = this.data.second - 1
      if (next === -1) {
        if (this.data.minute > 0) {
          this.setData({ second: 59 })
          this.setData({ minute: this.data.minute - 1 })
        } else {
          clearInterval(this.data.timer)
          this.showWrong()
          this.setData({
            showDJS: false
          })
        }
      } else {
        this.setData({ second: next })
      }
    }, 1000)
    this.setData({ timer: mid })
  },
  previousExam() {
    this.setData({ index: this.data.index - 1 })
    this.whichToFocus()
  },
  nextExam() {
    this.setData({ index: this.data.index + 1 })
    this.whichToFocus()
    if (!this.data.list[this.data.index]) {
      this.chuti()
    }
  },
  // 手工切换上一题下一题时决定让哪个输入框聚焦
  whichToFocus() {
    if (this.data.examTypes[this.data.typeIndex] !== '带余数除法') {
      this.setData({ isFocus: true })
    } else {
      const mid = this.data.list[this.data.index]
      if (!mid) {
        this.setData({ isShangFocus: true, isYuShuFocus: false })
      } else {
        const [shang] = mid[1].split('余')
        if (shang !== mid[2]) {
          this.setData({ isShangFocus: true, isYuShuFocus: false })
        } else {
          this.setData({ isShangFocus: false, isYuShuFocus: true })
        }
      }
    }
  },
  chuti() {
    const res = getExam(this.data.examTypes[this.data.typeIndex])
    if (this.checkRepeat(res[0])) {
      this.chuti()
    } else {
      this.pushList(res)
    }
  },
  // 检查出题是否与上一题重复,重复返回true,否则返回false
  checkRepeat(str: string) {
    if (this.data.index === 0) {
      return false
    } else {
      const pre = this.data.list[this.data.index - 1][0]
      if (str === pre) {
        return true
      } else {
        return false
      }
    }
  },
  pushList(res: string[]) {
    const mid = this.data.list
    const [ti, ans] = res
    mid.push([ti, '-1'])
    this.setData({ list: mid })
    setTimeout(() => {
      mid[this.data.index][1] = ans
      this.setData({ list: mid })
    }, 10);
  },
  setValue(e: AnyObject) {
    const mid = e.detail.value.trim()
    this.resetUserResult(mid)
    if (this.data.list[this.data.index][1] === mid) {
      this.nextExam()
      // 在手机端一次输入会执行两次setValue，得到正确答案后，index自增，再次执行setValue方法时，会把下一题的用户答案赋上这一题的正确答案，在此加一个定时器清空下一题的用户答案
      setTimeout(() => {
        // 这里能解决绝大多数异常，但是如果下一题答案与本题相同，则会导致另外的异常,解决方法是在出题时先给一个负数作为正确答案，定时后恢复正确答案。
        this.resetUserResult('')
      }, 0)
    }
  },
  setShangValue(e: AnyObject) {
    const mid = e.detail.value.trim()
    this.resetUserResult(mid)
    const res = this.checkShangYuShuResult()
    switch (res) {
      case 'wright':
        this.nextExam()
        setTimeout(() => {
          this.resetUserResult('')
        }, 0)
        break;
      case 'shang':
        this.setData({ isShangFocus: false, isYuShuFocus: true })
        break;
    }
  },
  setYuShuValue(e: AnyObject) {
    const mid = e.detail.value.trim()
    this.resetUserResult(mid, true)
    const res = this.checkShangYuShuResult()
    switch (res) {
      case 'wright':
        this.nextExam()
        setTimeout(() => {
          this.resetUserResult('', true)
        }, 0)
        break;
      case 'yuShu':
        this.setData({ isShangFocus: true, isYuShuFocus: false })
        break;
    }
  },
  checkShangYuShuResult() {
    const mid = this.data.list[this.data.index]
    const [shang, yuShu] = mid[1].split('余')
    if (shang === mid[2] && yuShu === mid[3]) {
      this.setData({ isShangFocus: true, isYuShuFocus: false })
      return 'wright'
    } else if (shang === mid[2]) {
      return 'shang'
    } else if (yuShu === mid[3]) {
      return 'yuShu'
    } else {
      return 'no'
    }
  },
  resetUserResult(val: string, isYuShu: boolean = false) {
    const mid = this.data.list[this.data.index]
    mid[!isYuShu ? 2 : 3] = val
    this.setData({ list: this.data.list })
  },
  showWrong() {
    let mid = []
    if (this.data.examTypes[this.data.typeIndex] !== '带余数除法') {
      mid = this.data.list.filter((item: any) => item[1] !== item[2])
    } else {
      mid = this.data.list.filter((item: any) => item[1] !== item[2] + '余' + item[3])
    }
    const allTest = this.data.list.length
    this.setData({
      allTest,
      allRight: allTest - mid.length,
      wrongList: mid
    })
  },
  // 暂存成绩至本地
  saveScoreToStorage() {
    clearTimeout(this.data.submitTimer)
    const midTimer=setTimeout(async () => {
      if (this.data.loading) { return }
      this.setData({ loading: true })
      const mid = {
        date: Date.now(),
        name: app.globalData.userInfo.openid,
        testMinute: this.data.time,
        totalNum: this.data.allTest,
        rightNum: this.data.allRight,
        type: this.data.examTypes[this.data.typeIndex]
      }
      wx.request({
        url: `https://www.liqiantw.icu:3000/score/add`, // 填入业务自定义路径和参数，根目录，就是 / 
        method: 'POST', // 按照自己的业务开发，选择对应的方法
        header: {
          Authorization: app.globalData.userInfo.token
        },
        data: mid,
        success:()=>{
          wx.showToast({
            title: '保存成功',
            icon: 'success',
            duration: 1000
          })
          this.setData({ loading: false })
          this.setData({ list: [], wrongList: [] })
        },
        fail:(error)=>{
          console.log(error);
          wx.showToast({
            title: '保存失败',
            icon: 'error',
            duration: 1000
          })
          this.setData({ loading: false })
        }
      })
    }, 300);
    this.setData({submitTimer:midTimer})
  },
  cancelSave() {
    this.setData({ list: [], wrongList: [] })
  },
  changeTestType(val: any) {
    this.setData({ typeIndex: Number(val.detail.value) })
  }
})
